import type { AxiosInstance, AxiosResponse } from "axios";
import axios from "axios";
import wxAdapter from "axios-miniprogram-adapter";
import { useConfigStore } from "@/store";

export interface HttpResponse<T = unknown> extends AxiosResponse {
  code?: number
  message: string
  data: T
  state?: number
}

let instance: AxiosInstance | null = null;

// #ifdef MP-WEIXIN
axios.defaults.adapter = wxAdapter;
// #endif

let baseURL = "/api"

// 避免远程开发的时候冲突
if (process.env.NODE_ENV == "development") {
  baseURL = "http://127.0.0.1:27173/api"
}
else{
  baseURL = "https://api.m.dnftools.com/"
}


export function defineRequest<T>(fn: (ax: AxiosInstance) => T) {
  if (!instance) {
    instance = axios.create({
      baseURL
    });

    instance.interceptors.request.use(
      (request) => {
        const configStore = useConfigStore();
        const token = configStore.token;
        request.headers.Client = "mobile"

        if (token) {
          request.headers["Access-Alter"] = token;
        }

        return request;
      },
      (error) => {
        // do something
        return Promise.reject(error);
      }
    );

    instance.defaults.headers.post["Content-Type"]
      = "application/json;charset=UTF-8";
    // instance.defaults.headers["Accept-Encoding"] = "gzip"
    // instance.defaults.headers["Content-Encoding"] = "gzip"
    // add response interceptors
    instance.interceptors.response.use(
      async (response: AxiosResponse<HttpResponse>) => {
        if (response.data.code === 500) {
          /* empty */
        }
        // 解密数据
        return response.data
      },
      async (error: Error) => {
        return Promise.reject(error);
      }
    );
  }

  return fn(Object.create(instance));
}
